import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

import App from './App.vue'
import router from './router'

let app: ReturnType<typeof createApp> | null = null

function createVueApp() {
  const instance = createApp(App)
  instance.use(ElementPlus)
  instance.use(createPinia())
  instance.use(router)
  return instance
}

// 供无界主应用调用的生命周期
export function mount(selector = '#app') {
  if (app) return
  app = createVueApp()
  // 等待路由就绪后再挂载，避免宿主环境下初始路由未解析完成导致空白
  const w = (typeof window !== 'undefined' ? (window as any) : {})
  const isHosted = !!(w.__POWERED_BY_WUJIE__ || w.__WUJIE)
  router.isReady().then(() => {
    app && app.mount(selector)
  })
}

export function unmount() {
  if (!app) return
  app.unmount()
  app = null
}

// 全局暴露，便于主应用通过 window 调用
// 无界常见约定：通过 window 标记或变量判断是否处于子应用模式
const w = (typeof window !== 'undefined' ? (window as any) : {})
const isHosted = !!(w.__POWERED_BY_WUJIE__ || w.__WUJIE)
if (isHosted) {
  // 兼容不同宿主约定：同时暴露带/不带末尾下划线的 API 名称
  w.__WUJIE_MOUNT__ = mount
  w.__WUJIE_UNMOUNT__ = unmount
  w.__WUJIE_MOUNT = mount
  w.__WUJIE_UNMOUNT = unmount
  // 由主应用控制 mount/unmount，不自动挂载
} else {
  // 独立运行（开发/生产）自动挂载到 #app
  mount('#app')
}
